package com.gtd.account

import com.gtd.ws.Renderer
import com.gtd.ws.RestException

class AccountController {
	private final String REST_ACTION_CREATE = "create"
  private final String REST_ACTION_AUTHENTICATE = "authenticate"
  private final String REST_ACTION_GET = "get"


  def springApplicationContext
  def accountService
  def sessionStorageService

  def supportedMethods = null // Supported methods
  def res


  def index = {
    if (params.rest_action != null) {
      switch(params.rest_action) {
        case REST_ACTION_AUTHENTICATE:
          authenticate()
          break
        case REST_ACTION_CREATE:
          create()
          break
        case REST_ACTION_GET:
          get()
          break
        default:
          def e = [
            code: RestException.CODE_NOT_SUPPORTED_ACTION,
            message: RestException.MSG_NOT_SUPPORTED_ACTION
          ]
          res = [
            error: e
          ]
      }
    } else {
      def e = [
        code: RestException.CODE_NO_ACTION_SPECIFIED,
        message: RestException.MSG_NO_ACTION_SPECIFIED
      ]
      res = [
        error: e
      ]
    }
    Renderer.render(this, res)
  }

  def create = {
    supportedMethods = ["POST"]

    if (supportedMethods.contains(request.method)) {
      if (accountService.create(params)) {
        res = [
          data: accountService.data,
          success: accountService.success
        ]
        //System.out.prinln("Create: id = " + session.userId)
      } else {
        res = [
          error: accountService.error
        ]
      }
    } else {
      def e = [
          code: RestException.CODE_NOT_SUPPORTED_METHOD,
          message: RestException.MSG_NOT_SUPPORTED_METHOD
        ]
        res = [
          error: e
        ]
    }
  }

  def authenticate = {
    supportedMethods = ["GET", "POST"]
    if (supportedMethods.contains(request.method)) {
      if (accountService.authenticate(params)) {
        res = [
          data: accountService.data,
          success: accountService.success
        ]

        //System.out.println("id: ${session.userId}")

      } else {
        res = [
          error: accountService.error
        ]
      }
    } else {
      def e = [
        code: RestException.CODE_NOT_SUPPORTED_METHOD,
        message: RestException.MSG_NOT_SUPPORTED_METHOD
      ]
      res = [
        error: e
      ]
    }
  }

  //Testing only
  def get = {
    if (accountService.get()) {
      res = [
        data: accountService.data
      ]
    }
  }

  def user = {

  }

  def setting = {

  }


  def activate = {

  }

}
